// 系统概览页面JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 初始化仪表盘
    initDashboard();
    
    // 初始化图表
    initCharts();
    
    // 初始化数据刷新
    initDataRefresh();
    
    // 初始化交互事件
    initDashboardEvents();
    
    // 添加滚动动画
    addScrollAnimations();
});

// 初始化仪表盘
function initDashboard() {
    console.log('初始化仪表盘...');
    
    // 模拟数据加载
    simulateDataLoading();
    
    // 添加统计卡片动画
    animateStatCards();
    
    // 初始化实时数据更新
    initRealTimeUpdates();
}

// 初始化图表
function initCharts() {
    // 初始化座位使用趋势图
    initUsageTrendChart();
    
    // 初始化区域分布饼图
    initAreaDistributionChart();
}

// 初始化座位使用趋势图
function initUsageTrendChart() {
    const ctx = document.getElementById('usageTrendChart');
    if (!ctx) return;
    
    // 模拟数据 - 最近7天的使用趋势
    const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    const usageData = [650, 720, 800, 780, 850, 920, 880];
    const capacityData = [1000, 1000, 1000, 1000, 1000, 1000, 1000];
    
    // 创建图表
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '实际使用数',
                    data: usageData,
                    borderColor: '#3498db',
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    borderWidth: 3,
                    tension: 0.3,
                    fill: true,
                    pointBackgroundColor: '#3498db',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                },
                {
                    label: '总容量',
                    data: capacityData,
                    borderColor: '#95a5a6',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    tension: 0,
                    fill: false,
                    pointRadius: 0,
                    pointHoverRadius: 0
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        boxWidth: 12,
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14
                    },
                    bodyFont: {
                        size: 13
                    },
                    displayColors: true,
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            label += context.parsed.y;
                            
                            // 添加使用率
                            if (context.datasetIndex === 0) {
                                const usageRate = Math.round((context.parsed.y / capacityData[context.dataIndex]) * 100);
                                label += ` (${usageRate}%)`;
                            }
                            
                            return label;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        font: {
                            size: 12
                        }
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        font: {
                            size: 12
                        },
                        callback: function(value) {
                            return value.toLocaleString();
                        }
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 初始化区域分布饼图
function initAreaDistributionChart() {
    const ctx = document.getElementById('areaDistributionChart');
    if (!ctx) return;
    
    // 模拟数据 - 区域分布
    const labels = ['A区', 'B区', 'C区', 'D区', 'E区'];
    const data = [320, 280, 220, 180, 256];
    const backgroundColor = [
        '#3498db',
        '#27ae60',
        '#f39c12',
        '#e74c3c',
        '#9b59b6'
    ];
    const borderColor = '#ffffff';
    const borderWidth = 2;
    
    // 创建图表
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: backgroundColor,
                borderColor: borderColor,
                borderWidth: borderWidth,
                hoverOffset: 10
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        pointStyle: 'circle',
                        font: {
                            size: 12
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14
                    },
                    bodyFont: {
                        size: 13
                    },
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = Math.round((value / total) * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            },
            cutout: '70%',
            animation: {
                animateScale: true,
                animateRotate: true,
                duration: 1000,
                easing: 'easeOutQuart'
            },
            hover: {
                mode: 'nearest',
                intersect: false
            }
        }
    });
}

// 模拟数据加载
function simulateDataLoading() {
    const loadingElements = document.querySelectorAll('.stat-value, .chart-container');
    
    loadingElements.forEach(element => {
        element.style.opacity = '0';
        element.style.transition = 'opacity 0.3s ease';
    });
    
    setTimeout(() => {
        loadingElements.forEach(element => {
            element.style.opacity = '1';
        });
    }, 300);
}

// 统计卡片动画
function animateStatCards() {
    const statValues = document.querySelectorAll('.stat-value');
    
    statValues.forEach((value, index) => {
        const targetValue = value.textContent.replace(/,/g, '');
        value.textContent = '0';
        
        setTimeout(() => {
            animateNumber(value, 0, parseInt(targetValue), 1500);
        }, 300 + index * 100);
    });
}

// 数字增长动画
function animateNumber(element, start, end, duration) {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        const currentValue = Math.floor(progress * (end - start) + start);
        element.textContent = currentValue.toLocaleString();
        
        if (progress < 1) {
            window.requestAnimationFrame(step);
        }
    };
    window.requestAnimationFrame(step);
}

// 初始化实时数据更新
function initRealTimeUpdates() {
    // 模拟实时数据更新
    setInterval(() => {
        updateRealtimeData();
    }, 30000); // 每30秒更新一次
}

// 更新实时数据
function updateRealtimeData() {
    console.log('更新实时数据...');
    
    // 这里可以模拟数据更新
    // 在实际项目中，这里会调用API获取最新数据
}

// 初始化数据刷新
function initDataRefresh() {
    const refreshButtons = document.querySelectorAll('.refresh-btn');
    
    refreshButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 添加旋转动画
            this.classList.add('rotating');
            
            // 模拟数据刷新
            setTimeout(() => {
                this.classList.remove('rotating');
                showToast('数据已刷新', 'success');
            }, 1000);
        });
    });
    
    // 添加旋转动画样式
    const style = document.createElement('style');
    style.textContent = `
        .refresh-btn.rotating {
            animation: rotate 1s linear;
        }
        
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
}

// 初始化仪表盘交互事件
function initDashboardEvents() {
    // 统计卡片点击事件
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach(card => {
        card.addEventListener('click', function() {
            const title = this.querySelector('h3').textContent;
            showToast(`查看${title}详情`, 'info');
            
            // 添加点击效果
            this.style.transform = 'scale(0.98)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    });
    
    // 图表控制按钮事件
    const controlBtns = document.querySelectorAll('.control-btn');
    controlBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除同组按钮的活跃状态
            const parent = this.parentElement;
            parent.querySelectorAll('.control-btn').forEach(b => {
                b.classList.remove('active');
            });
            
            // 添加当前按钮的活跃状态
            this.classList.add('active');
            
            // 这里可以根据按钮类型切换图表数据
            console.log('切换图表视图:', this.textContent.trim());
        });
    });
    
    // 表格行悬停效果增强
    const tableRows = document.querySelectorAll('.data-table tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('mouseenter', function() {
            this.style.backgroundColor = '#f8f9fa';
            this.style.transition = 'background-color 0.2s ease';
        });
        
        row.addEventListener('mouseleave', function() {
            this.style.backgroundColor = '';
        });
    });
    
    // 操作按钮事件
    const actionBtns = document.querySelectorAll('.action-btn');
    actionBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const action = this.classList.contains('view') ? '查看' : 
                         this.classList.contains('edit') ? '编辑' : 
                         this.classList.contains('delete') ? '删除' : 
                         this.classList.contains('cancel') ? '取消' : '操作';
            
            showToast(`${action}成功`, 'success');
        });
    });
}

// 添加滚动动画
function addScrollAnimations() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('scroll-visible');
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1
    });
    
    const animatedElements = document.querySelectorAll('.stat-card, .chart-card, .table-card');
    animatedElements.forEach(element => {
        element.classList.add('scroll-animate');
        observer.observe(element);
    });
    
    // 添加滚动动画样式
    const style = document.createElement('style');
    style.textContent = `
        .scroll-animate {
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.8s ease, transform 0.8s ease;
        }
        
        .scroll-animate.scroll-visible {
            opacity: 1;
            transform: translateY(0);
        }
    `;
    document.head.appendChild(style);
}

// 导出仪表盘数据
function exportDashboardData() {
    // 这里可以实现导出功能
    console.log('导出仪表盘数据');
    showToast('数据导出成功', 'success');
}

// 刷新所有图表
function refreshAllCharts() {
    // 在实际项目中，这里会重新加载并更新所有图表
    console.log('刷新所有图表');
    showToast('图表已刷新', 'success');
}

// 切换图表视图（周/月/年）
function switchChartView(view) {
    console.log('切换图表视图:', view);
    // 这里可以根据视图类型更新图表数据
}

// 获取系统状态
function getSystemStatus() {
    // 模拟获取系统状态
    return {
        status: 'normal',
        onlineUsers: 489,
        cpuUsage: '23%',
        memoryUsage: '45%',
        diskUsage: '78%',
        uptime: '30天2小时'
    };
}

// 更新系统状态显示
function updateSystemStatus() {
    const status = getSystemStatus();
    const statusIndicator = document.querySelector('.system-status i');
    const statusText = document.querySelector('.system-status span');
    
    if (statusIndicator && statusText) {
        if (status.status === 'normal') {
            statusIndicator.className = 'fas fa-circle text-success';
            statusText.textContent = '正常运行';
        } else if (status.status === 'warning') {
            statusIndicator.className = 'fas fa-circle text-warning';
            statusText.textContent = '警告';
        } else if (status.status === 'error') {
            statusIndicator.className = 'fas fa-circle text-danger';
            statusText.textContent = '错误';
        }
    }
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + R 刷新数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            refreshAllCharts();
        }
        
        // Ctrl/Cmd + E 导出数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
            e.preventDefault();
            exportDashboardData();
        }
        
        // 数字键1-7切换菜单项
        if (e.key >= '1' && e.key <= '7') {
            const navItems = document.querySelectorAll('.nav-item');
            const index = parseInt(e.key) - 1;
            if (navItems[index]) {
                const link = navItems[index].querySelector('.nav-link');
                if (link) {
                    link.click();
                }
            }
        }
    });
}

// 暴露公共方法
window.dashboard = {
    initDashboard,
    refreshAllCharts,
    exportDashboardData,
    switchChartView,
    updateSystemStatus
};

// 初始化键盘快捷键
addKeyboardShortcuts();

// 定期更新系统状态
setInterval(updateSystemStatus, 60000); // 每分钟更新一次